<template>
  <div class="timeAxisWrap" :style="timeAxisStyle">
    <div class="control_items">
      <!-- <div class="time_case">{{ currentTime }}
      </div> -->
      <div class="btns">
        <el-tooltip effect="light" content="向后" popper-class="el_tooltip" placement="top" :offset="10">
          <button class="pre_btn" @click="preHandle" :disabled="!hasTimeData">
            <svg-icon name="pre" style="
                width:20px;
                height:20px;
                color: #ffffff;
              " />
          </button>
        </el-tooltip>

        <el-tooltip effect="light" :content="store.curIsPlay ? controlBtn.suspendContent : controlBtn.playContent" 
          popper-class="el_tooltip" placement="top" :offset="10">
          <button class="play_btn" @click="playHandle" :disabled="!hasTimeData">
            <svg-icon :name="store.curIsPlay ? 'pause' : 'play'" style="
                width:20px;
                height:20px;
                margin-top: 2px;
                color: #ffffff;
              " />
          </button>
        </el-tooltip>
        <el-tooltip effect="light" content="向前" popper-class="el_tooltip" placement="top" :offset="10">
          <button class="next_btn" @click="nextHandle" :disabled="!hasTimeData">
            <svg-icon name="next" style="
                width:20px;
                height:20px;
                margin-top: 2px;
                color: #ffffff;
              " />
          </button>
        </el-tooltip>
      </div>
      <div class="time_interval">
        <span class="time_interval_title">倍速</span>
        <el-select v-model="store.timeIntervalValue" @change="changeStepHandle" size="small"
          :disabled="!hasTimeData">
          <el-option v-for="item in store.timentervalOptions" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </div>
    </div>
    <div class="axis">
      <div v-if="!hasTimeData" class="no-data-tip">请选择历史架次</div>
      <el-slider v-else v-model="satelliteValue" :show-tooltip="false" :min="0" :max="maxValue" :marks="marks"
        @change="onSliderChange" :disabled="!hasTimeData"></el-slider>
      <div v-if="hasTimeData" class="absolute top-0px nowTime" :style="{ left: `${progressPosition}%` }">
        {{ nowTime }}
      </div>
    </div>
  </div>
</template>

<script setup>
/**  
* @description 时间轴组件
* @param timentervalOptions 倍速选项
* @param startTime 开始时间（秒）
* @param endTime 结束时间（秒）
* @param interval 每大刻度间隔
* @param smallInterval 每个大刻度之间的小刻度数
* @methods timeChange 取到当前进度方法  
*/
import { ref, reactive, onMounted, nextTick, watch, watchEffect, computed, toRefs, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import moment from 'moment'
import { MultiAircraftReplayController } from "@/mapbox/mapbox_core/playback/index";
import timeAxisStore from "@/stores/modules/timeAxis";
import { getMap } from "@/mapbox/main/index.js";
import useInfoDataStore from "@/stores/modules/infoData";


const infoData = useInfoDataStore();

const store = timeAxisStore()
const route = useRoute();

// 添加计算属性判断是否有时间数据
const hasTimeData = computed(() => {
  return store.startTime > 0 && store.endTime > 0;
})

const timeAxisStyle = computed(() => {
  let fullScreenMenu = ['/home/index']
  let width = '100%'

  // if (!fullScreenMenu.includes(route.path)) {
  //   width = `calc(100vw - ${globalStore.isCollapse ? settings.asideMenuCollapseWidth : globalStore.menuWidth + 'px'})`
  // }

  return { width }
})

const controlBtn = reactive({
  playContent: '播放',
  suspendContent: '暂停'
})
watch(() => store.curIsPlay, (newVal) => {
  if (!newVal) {
    clearInterval(timer)
  }
})
const satelliteValue = ref(0)
let timer = null
// 初始化控制器
// let controller = null;

// 计算刻度
const marks = computed(() => {
  const markObj = {};
  // 计算时间总跨度
  const totalDuration = store.endTime - store.startTime;
  if (totalDuration <= 0) return markObj;

  // 计算跨天天数
  const startDate = new Date(store.startTime * 1000);
  const endDate = new Date(store.endTime * 1000);
  const daysDiff = Math.floor((endDate - startDate) / (24 * 60 * 60 * 1000));

  // 估算时间轴宽度并计算理想刻度数
  const containerWidth = document.documentElement.clientWidth * 0.8;
  const idealTickCount = Math.min(20, Math.max(5, Math.floor(containerWidth / 100)));

  // 计算大刻度间隔
  const majorInterval = calculateMajorInterval(totalDuration, daysDiff, idealTickCount);
  const minorInterval = majorInterval / store.smallInterval;

  // 向下取整到最近的整刻度开始
  const firstTickTime = Math.ceil(store.startTime / majorInterval) * majorInterval;

  // 添加主刻度和小刻度
  addTimeMarks(markObj, firstTickTime, majorInterval, minorInterval, daysDiff);

  // 确保起点和终点有刻度
  addEndpointMarks(markObj, totalDuration);

  return markObj;
});

// 计算大刻度间隔
const calculateMajorInterval = (totalDuration, daysDiff, idealTickCount) => {
  let interval = Math.ceil(totalDuration / idealTickCount);

  // 跨天超过1天，使用更大的时间间隔
  if (daysDiff > 1) {
    if (daysDiff <= 3) return Math.max(interval, 3600 * 6); // 至少6小时
    if (daysDiff <= 7) return Math.max(interval, 3600 * 12); // 至少12小时
    if (daysDiff <= 14) return Math.max(interval, 3600 * 24); // 至少1天
    if (daysDiff <= 30) return Math.max(interval, 3600 * 24 * 2); // 至少2天
    return Math.max(interval, 3600 * 24 * 5); // 至少5天
  }

  // 非跨天或只跨1天，使用标准时间单位
  if (interval <= 15) return 15; // 15秒
  if (interval <= 30) return 30; // 30秒
  if (interval <= 60) return 60; // 1分钟
  if (interval <= 300) return 300; // 5分钟
  if (interval <= 600) return 600; // 10分钟
  if (interval <= 900) return 900; // 15分钟
  if (interval <= 1800) return 1800; // 30分钟
  return 3600; // 1小时
};

// 添加时间刻度
const addTimeMarks = (markObj, firstTickTime, majorInterval, minorInterval, daysDiff) => {
  for (let time = firstTickTime; time <= store.endTime; time += majorInterval) {
    if (time >= store.startTime) {
      // 判断是否是整天或整小时
      const isDay = time % (24 * 3600) === 0;
      const isHour = time % 3600 === 0;

      markObj[time - store.startTime] = {
        label: formatTime(time, isDay ? 'day' : (isHour ? 'hour' : '')),
      };
    }

    // 只有在非跨天或间隔小于1天的情况下添加小刻度
    if (daysDiff <= 1 || majorInterval < 24 * 3600) {
      // 添加小刻度
      for (let i = 1; i < store.smallInterval; i++) {
        const smallTime = time + (i * minorInterval);
        if (smallTime <= store.endTime && smallTime >= store.startTime) {
          markObj[smallTime - store.startTime] = { label: '' };
        }
      }
    }
  }
};

// 添加起点和终点刻度
const addEndpointMarks = (markObj, totalDuration) => {
  if (!markObj[0] && store.startTime > 0) {
    markObj[0] = { label: formatTime(store.startTime, 'start') };
  }

  if (!markObj[totalDuration] && totalDuration > 0) {
    markObj[totalDuration] = { label: formatTime(store.endTime, 'end') };
  }
};

// 格式化时间，根据类型返回不同格式
const formatTime = (seconds, type) => {
  const date = new Date(seconds * 1000);
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const secondsStr = String(date.getSeconds()).padStart(2, '0');

  // 计算跨天天数
  const daysDiff = calculateDaysDifference();

  // 根据跨天情况和类型返回格式化的时间
  return formatTimeBasedOnSpan(daysDiff, type, month, day, hours, minutes, secondsStr);
};

// 计算开始和结束时间的天数差
const calculateDaysDifference = () => {
  const startDate = new Date(store.startTime * 1000);
  const endDate = new Date(store.endTime * 1000);
  return Math.floor((endDate - startDate) / (24 * 60 * 60 * 1000));
};

// 根据时间跨度和类型格式化时间
const formatTimeBasedOnSpan = (daysDiff, type, month, day, hours, minutes, seconds) => {
  if (daysDiff > 1) {
    // 多天跨越情况下的格式化
    if (type === 'day') return `${month}-${day}`;
    if (type === 'hour') return `${month}-${day} ${hours}:00`;
    if (type === 'start' || type === 'end') return `${month}-${day} ${hours}:${minutes}`;
    return `${hours}:${minutes}`;
  } else {
    // 单天或不跨天情况下的格式化
    if (type === 'day') return `${month}-${day}`;
    if (type === 'hour') return `${hours}:00`;
    if (type === 'start' || type === 'end' || seconds === '00') return `${hours}:${minutes}`;
    return `${hours}:${minutes}:${seconds}`;
  }
};

// 当前时间显示
const nowTime = computed(() => {
  const seconds = satelliteValue.value + store.startTime;
  const time = new Date(seconds * 1000);
  const month = String(time.getMonth() + 1).padStart(2, '0');
  const day = String(time.getDate()).padStart(2, '0');
  const hours = String(time.getHours()).padStart(2, '0');
  const minutes = String(time.getMinutes()).padStart(2, '0');
  const secondsStr = String(time.getSeconds()).padStart(2, '0');

  // 根据跨天情况返回不同格式
  const daysDiff = calculateDaysDifference();
  return daysDiff > 1
    ? `${month}-${day} ${hours}:${minutes}:${secondsStr}`
    : `${hours}:${minutes}:${secondsStr}`;
});

// 进度播放功能
const playHandle = (type = 'nextHandle') => {
  // 清除之前的定时器
  if (timer) {
    clearInterval(timer);
    timer = null;
  }

  if (type != 'doubleSpeed') {
    store.setCurIsPlay(!store.curIsPlay);
  }

  if (store.curIsPlay) {
    startPlayback(type);
  } else {
     store.controller.pause();
  }
};

// 开始播放
const startPlayback = (type) => {
  const maxVal = store.endTime - store.startTime;

  timer = setInterval(() => {
    if (type !== 'preHandle') {
      // 向前播放
      satelliteValue.value += 1;
      if (satelliteValue.value >= maxVal) {
        handlePlaybackEnd(maxVal);
      }
    } else {
      // 向后播放
      satelliteValue.value -= 1;
      if (satelliteValue.value <= 0) {
        handlePlaybackEnd(0);
      }
    }
    onSliderChange();
  }, (1000 / store.timeIntervalValue));

   store.controller.start();
};

// 处理播放结束
const handlePlaybackEnd = (value) => {
  satelliteValue.value = value;
  clearInterval(timer);
  store.setCurIsPlay(false);
};

// 滑块变化时的回调
const onSliderChange = (value) => {
  if (!store.startTime) return;

  // 确保值在有效范围内
  const maxVal = store.endTime - store.startTime;
  satelliteValue.value = Math.max(0, Math.min(satelliteValue.value, maxVal));

  // 更新控制器时间
  updateControllerTime();

  // 触发更新刻度样式
  updateMarksStyle();
};

// 更新控制器时间
const updateControllerTime = () => {
  const seconds = satelliteValue.value + store.startTime;
  const time = new Date(seconds * 1000);

  if ( store.controller) {
     store.controller.setCurrentTime(time);
    infoData.historyIndex = +new Date(seconds * 1000);

  }
};

const updateMarksStyle = () => {
  nextTick().then(() => {
    const marks_elements = document.getElementsByClassName('el-slider__stop')
    const marks_labels = document.getElementsByClassName('el-slider__marks-text')
    const currentValue = satelliteValue.value + store.startTime // 当前实际时间值

    for (let i = 0; i < marks_elements.length; i++) {
      // 从元素的 style.left 获取百分比值
      const leftPercentage = parseFloat(marks_elements[i].style.left)
      // 将百分比转换为实际时间值
      const totalDuration = store.endTime - store.startTime
      const markTime = store.startTime + (totalDuration * leftPercentage / 100)

      // 设置刻度高度
      if (marks_labels[i]?.innerHTML == '') {
        marks_elements[i].style.bottom = '25%'
        marks_elements[i].style.height = '50%'
        marks_elements[i].style.width = '1px'
      } else {
        marks_elements[i].style.height = '100%'
        marks_elements[i].style.width = '1.5px'
      }

      // 设置刻度和文字颜色 - 只有当前进度之前的变白色
      if (markTime <= currentValue) {
        marks_elements[i].style.background = '#FFFFFF'
        if (marks_labels[i]) {
          marks_labels[i].style.color = '#FFFFFF'
          marks_labels[i].style.fontWeight = '500'
        }
      } else {
        marks_elements[i].style.background = '#CCCCCC'
        if (marks_labels[i]) {
          marks_labels[i].style.color = '#CCCCCC'
          marks_labels[i].style.fontWeight = '400'
        }
      }
    }
  })
}

// 向后
const preHandle = () => {
  satelliteValue.value = Math.max(0, satelliteValue.value - 1);
  onSliderChange();
}
// 向前
const nextHandle = () => {
  const maxVal = store.endTime - store.startTime;
  satelliteValue.value = Math.min(maxVal, satelliteValue.value + 1);
  onSliderChange();
}
// 倍速
const changeStepHandle = (val) => {
  store.controller.setSpeed(val);

  playHandle('doubleSpeed')
}
// 滑动条改变
const progressPosition = computed(() => {
  return (satelliteValue.value / maxValue.value) * 100
})

const currentTime = computed(() => {
  const seconds = satelliteValue.value + store.startTime;
  const time = new Date(seconds * 1000);
  const year = time.getFullYear();
  const month = String(time.getMonth() + 1).padStart(2, '0');
  const day = String(time.getDate()).padStart(2, '0');
  const hours = String(time.getHours()).padStart(2, '0');
  const minutes = String(time.getMinutes()).padStart(2, '0');
  const secondsStr = String(time.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${secondsStr}`;
});

let ignoreNextUpdate = false;
// 最大值为结束时间
const maxValue = computed(() => store.endTime - store.startTime);

// watch(() => store.timeList, (newVal) => {
//   if (ignoreNextUpdate) {
//     ignoreNextUpdate = false;
//     return;
//   }

//   console.log(newVal, '222222222');
//   if (newVal && newVal.length > 0) {
//     const latestData = newVal[newVal.length - 1];
//     controller.addAircraft(latestData.id, latestData.data);

//     // 暂存当前播放状态
//     const wasPlaying = store.$state.curIsPlay;
//     if (wasPlaying) {
//       // 暂停播放
//       clearInterval(timer);
//       store.setCurIsPlay(false);
//     }

//     // 记录当前相对位置百分比
//     const currentPositionPercent = store.$state.startTime > 0 ?
//       (satelliteValue.value / (store.$state.endTime - store.$state.startTime)) : 0;

//     store.setTime({
//       startTime: controller.getEarliestStartTime(),
//       endTime: controller.getLatestEndTime(),
//     });
//     ignoreNextUpdate = true;
//     if (store.$state.startTime > 0 && store.$state.endTime > store.$state.startTime) {
//       const newValue = Math.round(currentPositionPercent * (store.$state.endTime - store.$state.startTime));
//       satelliteValue.value = Math.min(newValue, store.$state.endTime - store.$state.startTime);

//       const seconds = satelliteValue.value + store.$state.startTime;
//       controller.setCurrentTime(new Date(seconds * 1000));
//     }

//     if (wasPlaying) {
//       setTimeout(() => {
//         store.setCurIsPlay(true);
//         playHandle('doubleSpeed');
//       }, 100);
//     }
//   } else {
//     satelliteValue.value = 0;
//     if (timer) {
//       clearInterval(timer);
//     }
//     if (store.$state.curIsPlay) {
//       store.setCurIsPlay(false);
//     }
//   }
// }, {
//   deep: true,
//   flush: 'post' 
// })

watch(() => satelliteValue.value, (newVal) => {
  store.timeChange({
    time: (newVal + store.startTime) * 1000,
    sateValue: newVal
  });
  updateMarksStyle();
}, { immediate: true });

// 计算开始时间和结束时间的显示格式
const formattedStartTime = computed(() => formatTime(store.startTime, 'start'));
const formattedEndTime = computed(() => formatTime(store.endTime, 'end'));

/**
 * 根据ID移除航空器轨迹并更新时间轴
 * @param id 航空器ID
 */
const removeAircraftTrail = (id) => {
  console.log(id);

  // 检查ID是否存在
  if (!id || ! store.controller) return;

  const wasPlaying = store.curIsPlay;

  if (wasPlaying) {
    clearInterval(timer);
    store.setCurIsPlay(false);
  }

   store.controller.removeAircraft(id);

  // store.timeList = store.timeList.filter(item => item.id != id);

  if (store.timeList.length > 0) {
    store.setTime({
      startTime:  store.controller.getEarliestStartTime(),
      endTime:  store.controller.getLatestEndTime(),
    });

    const maxVal = store.endTime - store.startTime;
    satelliteValue.value = Math.min(satelliteValue.value, maxVal);

    const seconds = satelliteValue.value + store.startTime;
     store.controller.setCurrentTime(new Date(seconds * 1000));

    if (wasPlaying) {
      setTimeout(() => {
        store.setCurIsPlay(true);
        playHandle('doubleSpeed');
      }, 100);
    }
  } else {
    satelliteValue.value = 0;
    store.clearTimeAxis();
  }

  updateMarksStyle();
}

// 暴露方法供外部调用
defineExpose({
  removeAircraftTrail
});

onMounted(() => {
  updateMarksStyle()
  // store.setTime(
  //   {
  //     startTime: new Date("2024-11-14 08:33:42").getTime(),
  //     endTime: new Date("2024-11-14 09:53:42").getTime(),
  //   }
  // )

  // setTimeout(() => {
  //   controller = new MultiAircraftReplayController({
  //     defaultSpeed: store.$state.timeIntervalValue,
  //     cleanupInterval: 2000,
  //     showFullTrail: true,
  //     trailColor: "#ff0000",
  //     trailWidth: 3,
  //   });

  //   controller.init(getMap());
  //   controller.removeAllAircraft()
  // }, 1000);

  // 在窗口大小变化时重新计算刻度
  window.addEventListener('resize', () => {
    // 触发marks的重新计算
    nextTick().then(() => {
      updateMarksStyle();
    });
  })
})

onBeforeUnmount(() => {
  if ( store.controller) {
     store.controller.removeAllAircraft()
  }
})
</script>

<style lang="scss" scoped>
@forward './timeAxis';

// 下拉选择器css
:deep(.el-select) {
  width: 60px;
  height: 24px;
}

:deep(.el-input) {
  width: 60px;
  height: 24px;
  // border: none;
  font-size: 12px;
  --el-input-border-color: #5e83d4;
}

:deep(.el-select__caret) {
  color: #fff !important; //箭头颜色
}

:deep(.el-input__inner) {
  font-size: 12px;
  color: #fff;
}

:deep(.el-input__wrapper) {
  background: rgba(30, 85, 204, 0.64);
}

//时间滑块css
:deep(.el-slider) {
  //外框
  height: 32px;
  padding-top: 0;
}

:deep(.el-slider__runway) {
  //灰色底框
  height: 12px;
  border-radius: 0;
  margin: 0;
  // background: #a3bce2;
  background: rgba(163, 188, 226, 0.8);
}

:deep(.el-slider__bar) {
  //蓝色划过框
  height: 12px;
  border-radius: 0;
  margin: 0;
  background: rgba(30, 85, 204, 0.8);
}

:deep(.el-slider__button) {
  //按钮
  display: none;
}

/* 自定义刻度线的样式 */
:deep(.el-slider__stop) {
  position: absolute;
  bottom: 2%;
  height: 96%;
  width: 1px;
  border-radius: 0%;
  background: #CCCCCC;
  transition: background-color 0.3s ease;
}

:deep(.el-slider__marks-text) {
  font-size: 12px;
  color: #CCCCCC;
  transition: color 0.3s ease;
  margin-top: 15px;
}

.nowTime {
  position: absolute;
  top: 0px;
  width: 110px;
  text-align: center;
  font-size: 12px;
  padding: 1px 3px;
  transform: translateX(-50%);
  background-color: #fff;
  box-sizing: border-box;
  border-radius: 5px;
  display: block;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
  z-index: 10;

  &::after {
    content: '';
    position: absolute;
    width: 0;
    height: 0;
    border: 5px solid #fff;
    border-color: #fff transparent transparent transparent;
    bottom: -8px;
    left: 50%;
    transform: translateX(-55%);
  }
}

.time_case {
  margin-right: 10px;
}

.no-data-tip {
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #CCCCCC;
  font-size: 14px;
  background: rgba(163, 188, 226, 0.8);
  border-radius: 4px;
}
</style>
